/**
 * 
 */
package com.hoopchina.util.json;

import java.util.List;
import android.content.Context;
import android.net.Uri;
import android.os.Handler;

/**
 * JsonHandlerThread 
 * 获得json
 * @author Guo Baiyu
 */
public class JsonHandlerThread extends Thread {
	
    protected static final int  H_GET_JSON_OK    = 1;
    protected static final int  H_GET_JSON_START = 0;
    protected static final int  H_GET_JSON_ERROR = -1;

    private Context             mContext         = null;
    private List<String>        mJsonKeywordList = null;
    private String              mKeyWord         = null;
    private IJsonHandleObserver mObserver        = null;

    /**
	 * 
	 */
    public JsonHandlerThread( Context context, String strKeyWord ) {
    	mContext = context;
        mKeyWord = strKeyWord;
    }
    
    public void setObserver(IJsonHandleObserver observer) {
    	mObserver = observer;
    }

    /**
	 * 
	 */
    public void run() {
        loadJsonData();
    }

    private Handler mHandler = new Handler() {
		public void handleMessage(android.os.Message msg)
		{
			switch (msg.what)
			{
			case H_GET_JSON_START:
				mObserver.startGetJson();
				break;
			case H_GET_JSON_OK:
				mObserver.showJson(mJsonKeywordList);
				break;
			case H_GET_JSON_ERROR:
                mObserver.notifyGetJsonError(0);
				break;
			default:
				break;
			}

		};
     };

    /**
     * 加载json list
     * 
     * @param strKeyWord
     */
     @SuppressWarnings ( "unchecked" )
    public void loadJsonData() {
        if ( null == mContext || null == mKeyWord || mKeyWord.equals( "" )) {
            return;
        }
        mHandler.sendEmptyMessage( H_GET_JSON_START );

        // String kw = Uri.encode(strKeyWord);、、&prod=iphone_video&pre=data 
        SearchRemindJsonInfo sjr = new SearchRemindJsonInfo("http://nssug.baidu.com/su?wd="
                + Uri.encode( mKeyWord ) + "&ie=utf-8&prod=news");
        mJsonKeywordList =  ( List<String> ) sjr.getInfoFromJson();
        
        if ( null == mJsonKeywordList ) {
            mHandler.sendEmptyMessage( H_GET_JSON_ERROR );
        }
        else {
            mHandler.sendEmptyMessage( H_GET_JSON_OK );
        }
    }
}
